{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8b68549e-288e-40d5-b1c6-12df5f87033c",
   "metadata": {},
   "source": [
    "### MindSpore的多卡并行设计\n",
    "\n",
    "不同于Pytorch提供DataParallel的单进程多卡训练，MindSpore采用多进程并行的方式。其优势是不存在所有梯度需要汇集到0号卡而导致的多GPU显存占用不均匀问题。且单卡和多卡的训练代码不需要做太大的改动，仅需要通过数行代码配置启动即可。\n",
    "\n",
    "但此类设计需要进程间通信，且需要DataLoader(即mindspore.dataset)的支持。下面通过几个例子进行演示："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51fcc356-fd1c-44c8-9573-ac2775fffdc3",
   "metadata": {},
   "source": [
    "#### AllReduce\n",
    "将所有向量相加，并将结果广播给所有GPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9954cb92-f2ba-4d84-8423-f46d16f74e01",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "allreduce之前：[[2. 2.]] at rank 1\n",
      "allreduce之前：[[1. 1.]] at rank 0\n",
      "allreduce之后：[[3. 3.]] at rank 1\n",
      "allreduce之后：[[3. 3.]] at rank 0\n"
     ]
    }
   ],
   "source": [
    "!mpirun --allow-run-as-root -np 2 python allreduce.py"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93289ba1-2594-4c62-80ef-3291cc2b3fb6",
   "metadata": {},
   "source": [
    "#### AlltoAll\n",
    "将一个小批量数据均匀地分布在多个GPU上"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "b5a862c7-6e59-4860-a6fd-187c0c7dcf9d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alltoall之前：[0 1 2 3 4 5 6 7] at rank 0\n",
      "alltoall之前：[0 1 2 3 4 5 6 7] at rank 1\n",
      "alltoall之后：[4 5 6 7] at rank 1\n",
      "alltoall之后：[0 1 2 3] at rank 0\n"
     ]
    }
   ],
   "source": [
    "!mpirun --allow-run-as-root -np 2 python alltoall.py"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
